#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件    :run.py
@说明    :提供网页端的界面
@时间    :2021/02/03 16:01:27
@作者    :DanceDJ
@微信公众号    :给我一碗炒饭
@版本    :1.0
'''
import os,sys
import requests
import png
import socket
import shutil,time
from bs4 import BeautifulSoup
from flask import Flask, render_template
from flask import Flask, jsonify,json
from flask import request
import webbrowser

def app_path():
    """Returns the base application path."""
    if hasattr(sys, 'frozen'):
        # Handles PyInstaller
        return os.path.dirname(sys.executable)  #使用pyinstaller打包后的exe目录
    return os.path.dirname(__file__)                 #没打包前的py目录
t=app_path()
app = Flask(__name__,static_folder=t+'/static')
 
@app.route('/')
def index():
    return app.send_static_file('index.html')
 
@app.route('/gf')
def get_path_file():
    rgs = request.args.get("path")
    if(rgs=="" or rgs==None):
        return jsonify(code=0)
    if not os.path.isdir(rgs):
        return jsonify(code=0,message="该目录不存在",filepath=[])
    res=os.listdir(rgs)
    filepath=[]
    hz=['png','jpg','jpeg','PNG','JPG','JPEG']
    for f in res:
        suffix = f.split(".")
        if(len(suffix)==1 or suffix[1] not in hz):
            continue
        filepath.append(f)
    return jsonify(code=1,filepath=filepath)

@app.route('/create', methods=['POST'])
def create():
    a=request.get_data(as_text=True)
    data = json.loads(a)
    p=data['path']
    for i in data['data']:
        img=p+"/"+i['filename']
        id=i['id']
        png.circle(img,id)
    p=app_path()
    return jsonify(code=1,message=p+"/output")
    
def copydir(path):
    timestamp=int(time.time())
    source_path = os.path.abspath(path+'/static/game')
    target_path = os.path.abspath(path+'/static/'+str(timestamp))

    if not os.path.exists(target_path):
        os.makedirs(target_path)

    if os.path.exists(source_path):
        shutil.rmtree(target_path)

    shutil.copytree(source_path, target_path)
    return timestamp

@app.route('/play')
def copyimg():
    path = app_path()
    path2=path
    if(path=="" or path==None):
        return jsonify(code=0)
    if not os.path.isdir(path):
        return jsonify(code=0,message="该目录不存在")
    t=copydir(path)
    determination = path+'/static/'+str(t)+'/res/raw-assets/'
    if not os.path.exists(determination):
        os.makedirs(determination)
    path = path+'/output'
    folders= os.listdir(path)
    for folder in folders:
        if('.DS_Store' in folder):
            continue
        dir = path + '/' +  str(folder)
        files = os.listdir(dir)
        for file in files:
            source = dir + '/' + str(file)
            deter = determination+folder+"/" + str(file)
            shutil.copyfile(source, deter)
    return jsonify(code=1,message="资源文件生成成功",url="/static/"+str(t)+"/index.html",ip=getip(),path=path2+"/static/"+str(t))

def getip():
    try: 
        ip=""
        sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 
        sock.connect(('8.8.8.8',80)) 
        ip = sock.getsockname()[0] 
    finally: 
        sock.close() 
    return ip

if __name__ == '__main__':
    webbrowser.open('http://127.0.0.1:5000/', 0, False)
    app.run(host='0.0.0.0')
 
 
 
 
 

